package com.sugon.modules.excel.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.sugon.consts.DevInspectInterval;
import com.sugon.entity.InspectionInstitutionEntity;
import com.sugon.entity.SpecialDevPressureChannelEntity;
import com.sugon.entity.SysDeptEntity;
import com.sugon.modules.excel.IExcelHandler;
import com.sugon.modules.excel.dto.PressureChannelImportParamDTO;
import com.sugon.service.InspectionInstitutionService;
import com.sugon.service.SpecialDevPressureChannelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.List;

/**
 * 特种设备-压力管道台账Excel导入Handler
 *
 * @author YuXD
 * @since 2021-09-18
 */
@Service("pressureChannelExcelHandler")
public class PressureChannelExcelHandler extends AbstractExcelHandler implements IExcelHandler {

    @Autowired
    private SpecialDevPressureChannelService specialDevPressureChannelService;
    @Autowired
    private InspectionInstitutionService inspectionInstitutionService;

    /**
     * @param excelInputStream excel输入流
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int importExcelFromStream(InputStream excelInputStream) throws Exception {
        // 获取导入配置
        ImportParams importParams = getImportParams();
        // 从上传文件中读取起重设备台账列表
        List<PressureChannelImportParamDTO> pressureChannelAccountList = ExcelImportUtil.importExcel(excelInputStream, PressureChannelImportParamDTO.class, importParams);
        if (CollectionUtil.isEmpty(pressureChannelAccountList)) {
            return 0;
        }
        int importRows = 0;

        SpecialDevPressureChannelEntity pressureChannel = null;
        CopyOptions copyOptions = CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true);
        for (PressureChannelImportParamDTO param : pressureChannelAccountList) {
            // 是否更新校验记录
            boolean isUpdateCheckRecord = false;
            // 尝试获取设备信息
            String deviceId = param.getDeviceId();
            if (StrUtil.isNotEmpty(deviceId)) {
                pressureChannel = specialDevPressureChannelService.queryObject(deviceId);
            }
            if (pressureChannel == null) {
                pressureChannel = new SpecialDevPressureChannelEntity();
            }
            // 只有最近一次检验周期不为空，且DB中特种设备最近一次校验日期为空或者小于最近一次检验周期时，需要生成特种设备校验记录
            if (param.getLatestInspectDate() != null) {
                if (pressureChannel.getLatestInspectDate() == null || pressureChannel.getLatestInspectDate().before(param.getLatestInspectDate())) {
                    isUpdateCheckRecord = true;
                    Assert.notBlank(param.getInspectUnitName());
                    // 校验特种设备校验机构是否存在
                    InspectionInstitutionEntity inpsectUnit = inspectionInstitutionService.queryObjectByName(param.getInspectUnitName());
                    Assert.notNull(inpsectUnit, "序号{}中的检验机构不存在，请确认！", param.getInspectUnitName());
                    pressureChannel.setInspectUnit(inpsectUnit.getId());
                }
            }
            BeanUtil.copyProperties(param, pressureChannel, copyOptions);
            // 设置使用单位
            String userDeptName = param.getUserDeptName();
            if (StrUtil.isNotEmpty(userDeptName)) {
                SysDeptEntity dept = getDeptByName(userDeptName);
                if (dept != null) {
                    pressureChannel.setUserDept(dept.getDeptId());
                }
            }
            // 设置特种设备检验周期
            String inspectIntervalDesc = param.getInspectIntervalDesc();
            if (StrUtil.isNotEmpty(inspectIntervalDesc)) {
                DevInspectInterval inspectInterval = DevInspectInterval.getMonthsByDesc(inspectIntervalDesc);
                if (inspectInterval != null) {
                    pressureChannel.setInspectInterval(inspectInterval.getMonths());
                }
            }
            int rows = 0;
            if (StrUtil.isNotEmpty(pressureChannel.getId())) {
                rows = specialDevPressureChannelService.update(pressureChannel);
            } else {
                rows = specialDevPressureChannelService.save(pressureChannel);
            }
            if (rows > 0) {
                importRows += 1;
                if (isUpdateCheckRecord) {
                    // 生成下一次检测记录
                    generateCheckRecord("PRESSURE_CHANNEL", pressureChannel.getId(), param.getInspectReportNo(), param.getLatestInspectDate(), pressureChannel.getInspectUnit());
                }
            }
            pressureChannel = null;
        }
        return importRows;
    }

    /**
     * 设置导入参数
     *
     * @return
     */
    @Override
    public ImportParams getImportParams() {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(2);
        params.setKeyIndex(0);
        return params;
    }

}
